<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>查找数组中出现次数最多的元素</title>
</head>
<body>
<h1>查找数组中出现次数最多的元素</h1>

<script>
    /**
     * 查找数组中出现次数最多的元素
     * @param {Array} arr - 输入的数组，元素可以是字符串或数字
     * @returns {*} 出现次数最多的元素，如果有多个则返回第一个出现的
     */
    function findMostFrequentElement(arr) {
        // 使用对象作为计数器
        const counter = {};

        // 记录每个元素第一次出现的位置
        const firstOccurrence = {};

        // 统计每个元素出现的次数
        for (let i = 0; i < arr.length; i++) {
            const element = arr[i];

            // 如果是第一次遇到该元素，记录其首次出现位置
            if (counter[element] === undefined) {
                counter[element] = 1;
                firstOccurrence[element] = i;
            } else {
                // 增加计数
                counter[element]++;
            }
        }

        // 查找出现次数最多的元素
        let mostFrequentElement = null;
        let maxCount = 0;
        let earliestIndex = Infinity;

        for (const element in counter) {
            const count = counter[element];

            // 如果当前元素出现次数更多，或者次数相同但出现更早
            if (count > maxCount || (count === maxCount && firstOccurrence[element] < earliestIndex)) {
                mostFrequentElement = element;
                maxCount = count;
                earliestIndex = firstOccurrence[element];
            }
        }

        // 处理数字类型元素
        if (mostFrequentElement !== null) {
            // 尝试转换为数字
            const num = Number(mostFrequentElement);
            if (!isNaN(num) && arr.includes(num)) {
                return num;
            }

            // 处理字符串"null"、"undefined"、"true"、"false"
            if (mostFrequentElement === "null" && arr.includes(null)) {
                return null;
            }
            if (mostFrequentElement === "undefined" && arr.includes(undefined)) {
                return undefined;
            }
            if (mostFrequentElement === "true" && arr.includes(true)) {
                return true;
            }
            if (mostFrequentElement === "false" && arr.includes(false)) {
                return false;
            }
        }

        return mostFrequentElement;
    }

    // 更简洁的实现方式
    function findMostFrequentElementSimple(arr) {
        if (arr.length === 0) return undefined;

        // 使用对象作为计数器
        const counter = {};

        // 统计每个元素出现的次数
        for (let i = 0; i < arr.length; i++) {
            const element = arr[i];
            // 将元素转换为字符串作为键
            const key = JSON.stringify(element);
            counter[key] = counter[key] ? counter[key] + 1 : 1;
        }

        // 查找出现次数最多的元素
        let mostFrequentKey = "";
        let maxCount = 0;

        for (const key in counter) {
            if (counter[key] > maxCount) {
                mostFrequentKey = key;
                maxCount = counter[key];
            }
        }

        // 返回原始元素
        for (let i = 0; i < arr.length; i++) {
            const element = arr[i];
            if (JSON.stringify(element) === mostFrequentKey) {
                return element;
            }
        }

        return undefined;
    }

    // 最优化实现
    function findMostFrequentElement(arr) {
        if (arr.length === 0) return undefined;

        // 使用 Map 作为计数器（Map 可以正确处理各种数据类型）
        const counter = new Map();

        // 统计每个元素出现的次数
        for (const element of arr) {
            counter.set(element, (counter.get(element) || 0) + 1);
        }

        // 查找出现次数最多的元素
        let mostFrequentElement = arr[0];
        let maxCount = 1;

        for (const [element, count] of counter) {
            if (count > maxCount) {
                mostFrequentElement = element;
                maxCount = count;
            }
        }

        // 如果有多个元素出现次数相同，找到第一个出现的
        let earliestIndex = arr.indexOf(mostFrequentElement);
        for (const [element, count] of counter) {
            if (count === maxCount) {
                const index = arr.indexOf(element);
                if (index < earliestIndex) {
                    mostFrequentElement = element;
                    earliestIndex = index;
                }
            }
        }

        return mostFrequentElement;
    }

    // 测试用例
    console.log("--- 测试用例 ---");

    // 测试数字数组
    const numbers = [1, 2, 3, 2, 2, 4, 5, 1];
    console.log("数字数组:", numbers);
    console.log("出现次数最多的元素:", findMostFrequentElement(numbers));

    // 测试字符串数组
    const strings = ["apple", "banana", "apple", "orange", "banana", "apple"];
    console.log("字符串数组:", strings);
    console.log("出现次数最多的元素:", findMostFrequentElement(strings));

    // 测试混合数组
    const mixed = [1, "1", 1, "hello", "world", "hello", 2, 2];
    console.log("混合数组:", mixed);
    console.log("出现次数最多的元素:", findMostFrequentElement(mixed));

    // 测试相同频率元素
    const sameFrequency = ["a", "b", "a", "c", "b"]; // a和b都出现2次，但a先出现
    console.log("相同频率数组:", sameFrequency);
    console.log("出现次数最多的元素:", findMostFrequentElement(sameFrequency));
</script>
</body>
</html>
